package handler

import (
	"bytes"
	"fmt"
	"github.com/gin-gonic/gin"
	"io"
	"io/ioutil"
	"log"
	"loveserver/errno"
	"loveserver/model"
	"strconv"
)

type ListWords struct {
	Total    uint64              `json:"total"`
	DataList []model.WordsModel `json:"dataList"`
}

func FetchAllWords(c *gin.Context) {
	var words model.WordsModel
	count, thewords, err := words.GetAll()
	if err != nil {
		SendResponse(c, errno.ErrDatabase, nil)
		return
	}

	SendResponse(c, nil, ListWords{
		Total:    count,
		DataList: thewords,
	})
}

func FetchSingleWords(c *gin.Context) {
	var word model.WordsModel
	var err error

	id, _ := strconv.Atoi(c.Param("id"))
	word.ID = uint(id)

	if word, err = word.Get(); err != nil {
		SendResponse(c, errno.ErrDatabase, nil)
		return
	}
	SendResponse(c, nil, word)
}


// create a word
func AddWords(c *gin.Context) {

	words := model.WordsModel{
		Name: 	   c.PostForm("name"),
		Object:     c.PostForm("object"),
		Title:   c.PostForm("title"),
		Content:  c.PostForm("content"),
		Summary:  c.PostForm("summary"),
	}

	//json绑定
	err :=c.BindJSON(&words)
	if err!=nil{
		log.Fatal(err.Error())
		return
	}

	// * 创建一条记录，错误处理
	if err := words.Create(); err != nil {
		SendResponse(c, errno.ErrDatabase, nil)
		return
	}

	// * 返回结果
	SendResponse(c, nil, "create successful.")
}

//用户地址上链
func SetUserLocation(c *gin.Context)  {
	buf := &bytes.Buffer{}
	tea := io.TeeReader(c.Request.Body, buf)
	body, err := ioutil.ReadAll(tea)
	if err!=nil{
		log.Fatal(err.Error())}
	data:=string(body)
	fmt.Println(body)
	//上链函数
	message,err:=model.SetLocation(data)
	if err != nil {
		SendResponse(c, errno.ErrDatabase, nil)
		return
	}
	if (message=="SUCCESS"){
		var suc string="用户地址上链成功！"
		SendResponse(c, nil, suc)} else {
		var faild string="上链失败！"
		SendResponse(c, nil, faild)}
}



//通过订单号查询用户地址
func GetUserLocation(c *gin.Context)  {
	var orderid model.QueryLocation
	err:=c.BindJSON(&orderid) //json绑定获取参数
	fmt.Println(orderid)
	if err != nil {
		SendResponse(c, errno.ErrDatabase, nil)
		return
	}
	message,err:=model.GetLocation(orderid.OrderId)
	if err != nil {
		SendResponse(c, errno.ErrDatabase, nil)
		return
	}
	fmt.Println(message)
	SendResponse(c, nil, message)
}

//誓言上链
func SetSwear(c *gin.Context) {
	swear:= model.SwearModel{}
	//json绑定
	err :=c.BindJSON(&swear)
	if err!=nil{
		log.Fatal(err.Error())
		return
	}

	message,err :=model.SetSwear(swear)
	if err != nil {
		SendResponse(c, errno.ErrDatabase, nil)
		return
	}
	if (message=="SUCCESS"){
		var suc string="誓言上链成功！"
		SendResponse(c, nil, suc)} else {
		var faild string="上链失败！"
		SendResponse(c, nil, faild)}

}

//通过誓言人查找誓言内容
func Get(c *gin.Context)  {

	var getswearmodel model.GetSwearModel
	err:=c.BindJSON(&getswearmodel) //json绑定获取参数
	if err != nil {
		SendResponse(c, errno.ErrDatabase, nil)
		return
	}
	message,err:=model.GetSwear(getswearmodel.SwearMan)
	if err != nil {
		SendResponse(c, errno.ErrDatabase, nil)
		return
	}
	fmt.Println(message)
	SendResponse(c, nil, message)
}